package com.galaxy.stock.utils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
//import com.ruoyi.common.utils.DateUtils;

import com.ruoyi.common.exception.UtilException;
import com.ruoyi.common.utils.StringUtils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class RuntimeExecUtils {
    private static final Logger log = LoggerFactory.getLogger(RuntimeExecUtils.class);

    public static void process(String execFile, String... args) {
        try {
            String[] arguments;
            if (StringUtils.isEmpty(execFile)) {
                throw new UtilException("execFile is empty!");
            }
            if (execFile.toLowerCase().endsWith(".sh")) {
                arguments = new String[(args.length + 2)];
                arguments[0] = "sh";
                arguments[1] = execFile;
                for (int i = 0; i < args.length; i++) {
                    arguments[i + 2] = args[i];
                }
            } else if (execFile.toLowerCase().endsWith(".bat")) {
                arguments = new String[(args.length + 1)];
                arguments[0] = execFile;
                for (int i = 0; i < args.length; i++) {
                    arguments[i + 1] = args[i];
                }
            } else {
                throw new UtilException("execFile is wrong type,It must be .bat or .sh!");
            }

            Process process = Runtime.getRuntime().exec(arguments);
            BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8"));

            String line = null;
            String lastLine = null;
            while ((line = in.readLine()) != null) {
                log.info(line);
                lastLine = line;
            }

            in.close();
            // java代码中的process.waitFor()返回值为0表示我们调用python脚本成功，
            // 返回值为1表示调用python脚本失败，这和我们通常意义上见到的0与1定义正好相反
            int re = process.waitFor();
            log.info("result code:{}", String.valueOf(re));
            if (re != 0) {
                throw new UtilException("call python error! Error info maybe:" + lastLine);
            }
        } catch (Exception e) {
            log.error("RuntimeExecUtils.process fail:", e);
            throw new UtilException(e);
        }
    }

    // public static void main(String[] args) {
    // System.out.println(DateUtils.dateTime());
    // RuntimeExecUtils.process("D:/Work/sourcecode/stock/bin/run.bat", "20200901",
    // "20200901");
    // }

}
